package com.le.tester.tip.timedtask;

import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDate;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * createTime：2022/10/13 13:48
 * description：线程等待实现轮询处理
 */
public class ThreadWait {

    public static void main(String[] args) throws InterruptedException {

        //设定时间间隔为500ms(time unit is mill second)
        final long timeInterval = 500L;
        final long finalCount = 30L;
        AtomicLong addCount = new AtomicLong(0L);
        AtomicBoolean valve = new AtomicBoolean(Boolean.FALSE);
        //这边采用招商银行聚合支付开发文档的建议，超时时间设置为15s
        //这边将会循环30次

        //基于effectiveJava3的建议中，for循环会优于while
        for (int i = 0; i < finalCount; i++) {
            LocalDateTime start = LocalDateTime.now();
            System.out.println("start time is " + start);

            //业务逻辑
            System.out.println("current count is " + i);

            //不想使用这个线程的休眠来达到轮询的实现
            TimeUnit.MILLISECONDS.sleep(timeInterval);

            LocalDateTime end = LocalDateTime.now();
            System.out.println("duration time is " + ChronoUnit.MILLIS.between(start, end));

            //假定在第10次的时候获取到预期的值
            if (i == 10) {
                valve.set(Boolean.TRUE);
                break;
            }
        }

    }
}
